package top.huiwow.utils;

import org.bukkit.entity.Arrow;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import top.huiwow.GameCore;
import top.huiwow.managers.GamePlayer;

public class Validates {
    /**
     *Everytime this is used,need to check if it's null,
     * just like:
     * if (plugin==null){
     *     plugin=GameCore.getInstance();
     * }
     */
    static GameCore plugin=null;

    /**
     * this is used when player damage an entity.
     */
    public static GamePlayer validateP(EntityDamageByEntityEvent event) {
        if (plugin==null){
            plugin=GameCore.getInstance();
        }
        if (event.isCancelled()) {
            return null;
        }
        if (!(event.getDamager() instanceof Player) && !(event.getDamager() instanceof Arrow)) return null;

        Player player;

        if (event.getDamager() instanceof Arrow) {
            Arrow arrow = (Arrow) event.getDamager();

            if (arrow.getShooter() instanceof Player) {
                player = (Player) arrow.getShooter();

                if (player == event.getEntity()) return null;
            } else {
                return null;
            }

        } else {
            player = (Player) event.getDamager();
        }


        if (event.getDamage() == 0 || event.isCancelled()) return null;
        return plugin.getGamePlayerManager().get(player.getUniqueId());
    }

    /**
     * this is used when player is damaged by an entity.
     */
    public static LivingEntity validateE(EntityDamageByEntityEvent event) {
        if (plugin==null){
            plugin=GameCore.getInstance();
        }
        if (event.isCancelled()) {
            return null;
        }
        if (!(event.getDamager() instanceof LivingEntity) && !(event.getDamager() instanceof Projectile)) return null;
        if (!(event.getEntity() instanceof Player)) return null;
        LivingEntity damager;

        if (event.getDamager() instanceof Projectile) {
            Projectile projectile = (Projectile) event.getDamager();

            if (projectile.getShooter() instanceof LivingEntity) {
                damager = (LivingEntity) projectile.getShooter();

                if (damager == event.getEntity()) return null;
            } else {
                return null;
            }

        } else {
            damager = (LivingEntity) event.getDamager();
        }


        if (event.getDamage() == 0 || event.isCancelled()) return null;
        return damager;
    }
}
